package com.tencreat.common.core;


import com.tencreat.common.core.constants.HttpStatus;
import com.tencreat.common.core.exception.BaseException;
import com.tencreat.common.core.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.security.auth.login.AccountExpiredException;
import java.nio.file.AccessDeniedException;

/**
 * 全局异常处理器
 *
 * @Company: 深圳腾创互联科技有限公司
 * @link: https://tencreat.com/#/
 * @author tencreat
 */
@RestControllerAdvice
public class GlobalExceptionHandler
{
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 基础异常
     */
    @ExceptionHandler(BaseException.class)
    public HttpResult baseException(BaseException e)
    {
        return HttpResult.error(e.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(CustomException.class)
    public HttpResult businessException(CustomException e)
    {
        if (StringUtils.isEmpty(e.getCode()))
        {
            return HttpResult.error(e.getMessage());
        }
        return HttpResult.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public HttpResult handlerNoFoundException(Exception e)
    {
        log.error(e.getMessage(), e);
        return HttpResult.error(HttpStatus.NOT_FOUND, "路径不存在，请检查路径是否正确");
    }


    @ExceptionHandler(Exception.class)
    public HttpResult handleException(Exception e)
    {
        log.error(e.getMessage(), e);
        return HttpResult.error(e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public HttpResult validatedBindException(BindException e)
    {
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return HttpResult.error(message);
    }

    /**
     * 请求参数格式错误
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public HttpResult expHandle(HttpMessageNotReadableException e) {
        log.error(e.getMessage(), e);
        String msg = e.getMessage();
        int start = msg.indexOf("[\"");
        int end = msg.indexOf("\"]");
        if (start != -1 && end != -1) {
            msg = msg.substring(start + 2, end);
        }
        return HttpResult.error("请求参数格式错误：" + msg);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object validExceptionHandler(MethodArgumentNotValidException e)
    {
        String messageStr = e.getMessage();
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        int start = messageStr.indexOf("field '");
        int end = messageStr.indexOf("':");
        if (start != -1 && end != -1) {
            messageStr = messageStr.substring(start + 7, end);
        } else {
            messageStr = "";
        }
        return HttpResult.error(messageStr + message);
    }

}
